import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
import "../../components" as Components
import "../../styles" as Styles

Rectangle {
    id: vehicleDataGrid

    // 自定义属性
    property var agvList: []
    property var selectedAgv: null
    property var sortColumn: "id"
    property bool sortAscending: true

    // 信号
    signal agvSelected(var agv)
    signal agvDoubleClicked(var agv)
    signal agvAction(string action, var agv)

    color: "transparent"

    // 表格布局
    ColumnLayout {
        anchors.fill: parent
        spacing: 0

        // 表格头部
        Rectangle {
            Layout.fillWidth: true
            Layout.preferredHeight: 40
            color: Styles.Theme.backgroundSecondary
            border.color: Styles.Theme.border
            border.width: 1

            RowLayout {
                anchors.fill: parent
                anchors.leftMargin: Styles.Theme.spacingSmall
                anchors.rightMargin: Styles.Theme.spacingSmall
                spacing: 0

                Components.DataGridHeader {
                    text: qsTr("AGV ID")
                    Layout.preferredWidth: 80
                    sortable: true
                    sortColumn: "id"
                    currentSortColumn: vehicleDataGrid.sortColumn
                    sortAscending: vehicleDataGrid.sortAscending
                    onSort: function(column, ascending) {
                        vehicleDataGrid.sortColumn = column
                        vehicleDataGrid.sortAscending = ascending
                        sortAgvs()
                    }
                }

                Rectangle { width: 1; Layout.fillHeight: true; color: Styles.Theme.border }

                Components.DataGridHeader {
                    text: qsTr("状态")
                    Layout.preferredWidth: 100
                    sortable: true
                    sortColumn: "status"
                    currentSortColumn: vehicleDataGrid.sortColumn
                    sortAscending: vehicleDataGrid.sortAscending
                    onSort: function(column, ascending) {
                        vehicleDataGrid.sortColumn = column
                        vehicleDataGrid.sortAscending = ascending
                        sortAgvs()
                    }
                }

                Rectangle { width: 1; Layout.fillHeight: true; color: Styles.Theme.border }

                Components.DataGridHeader {
                    text: qsTr("电量")
                    Layout.preferredWidth: 80
                    sortable: true
                    sortColumn: "battery"
                    currentSortColumn: vehicleDataGrid.sortColumn
                    sortAscending: vehicleDataGrid.sortAscending
                    onSort: function(column, ascending) {
                        vehicleDataGrid.sortColumn = column
                        vehicleDataGrid.sortAscending = ascending
                        sortAgvs()
                    }
                }

                Rectangle { width: 1; Layout.fillHeight: true; color: Styles.Theme.border }

                Components.DataGridHeader {
                    text: qsTr("位置")
                    Layout.fillWidth: true
                    sortable: true
                    sortColumn: "position"
                    currentSortColumn: vehicleDataGrid.sortColumn
                    sortAscending: vehicleDataGrid.sortAscending
                    onSort: function(column, ascending) {
                        vehicleDataGrid.sortColumn = column
                        vehicleDataGrid.sortAscending = ascending
                        sortAgvs()
                    }
                }

                Rectangle { width: 1; Layout.fillHeight: true; color: Styles.Theme.border }

                Components.DataGridHeader {
                    text: qsTr("任务")
                    Layout.preferredWidth: 80
                    sortable: true
                    sortColumn: "currentTask"
                    currentSortColumn: vehicleDataGrid.sortColumn
                    sortAscending: vehicleDataGrid.sortAscending
                    onSort: function(column, ascending) {
                        vehicleDataGrid.sortColumn = column
                        vehicleDataGrid.sortAscending = ascending
                        sortAgvs()
                    }
                }
            }
        }

        // 表格内容
        ScrollView {
            Layout.fillWidth: true
            Layout.fillHeight: true
            clip: true

            ListView {
                id: agvListView
                model: agvList
                currentIndex: -1

                delegate: Rectangle {
                    width: agvListView.width
                    height: 60
                    color: {
                        if (selectedAgv && modelData.id === selectedAgv.id) {
                            return Styles.Theme.backgroundSelected
                        }
                        return index % 2 === 0 ? "transparent" : Styles.Theme.backgroundAlternate
                    }
                    border.color: selectedAgv && modelData.id === selectedAgv.id ? Styles.Theme.primary : "transparent"
                    border.width: 1

                    RowLayout {
                        anchors.fill: parent
                        anchors.leftMargin: Styles.Theme.spacingSmall
                        anchors.rightMargin: Styles.Theme.spacingSmall
                        spacing: 0

                        // AGV ID
                        ColumnLayout {
                            Layout.preferredWidth: 80
                            spacing: 2

                            Text {
                                text: modelData.id || ""
                                color: Styles.Theme.textPrimary
                                font.pixelSize: Styles.Theme.fontSizeSmall
                                font.weight: Styles.Theme.fontWeightMedium
                                elide: Text.ElideRight
                            }

                            Text {
                                text: modelData.model || ""
                                color: Styles.Theme.textSecondary
                                font.pixelSize: 10
                                elide: Text.ElideRight
                            }
                        }

                        Rectangle { width: 1; Layout.fillHeight: true; color: Styles.Theme.border; opacity: 0.3 }

                        // 状态
                        ColumnLayout {
                            Layout.preferredWidth: 100
                            spacing: 2

                            Rectangle {
                                Layout.preferredWidth: 90
                                Layout.preferredHeight: 20
                                radius: 10
                                color: getAgvStatusColor(modelData.status)

                                RowLayout {
                                    anchors.centerIn: parent
                                    spacing: 4

                                    Text {
                                        text: getAgvStatusIcon(modelData.status)
                                        color: Styles.Theme.textOnPrimary
                                        font.pixelSize: 10
                                    }

                                    Text {
                                        text: getAgvStatusText(modelData.status)
                                        color: Styles.Theme.textOnPrimary
                                        font.pixelSize: 10
                                    }
                                }
                            }

                            // 维护模式指示
                            Rectangle {
                                Layout.preferredWidth: 60
                                Layout.preferredHeight: 14
                                radius: 7
                                color: Styles.Theme.warning
                                visible: modelData.maintenanceMode

                                Text {
                                    anchors.centerIn: parent
                                    text: qsTr("维护")
                                    color: Styles.Theme.textOnPrimary
                                    font.pixelSize: 8
                                }
                            }
                        }

                        Rectangle { width: 1; Layout.fillHeight: true; color: Styles.Theme.border; opacity: 0.3 }

                        // 电量
                        ColumnLayout {
                            Layout.preferredWidth: 80
                            spacing: 2

                            // 电量进度条
                            Rectangle {
                                Layout.preferredWidth: 70
                                Layout.preferredHeight: 16
                                color: Styles.Theme.backgroundAlternate
                                radius: 8
                                border.color: Styles.Theme.border
                                border.width: 1

                                Rectangle {
                                    anchors.left: parent.left
                                    anchors.top: parent.top
                                    anchors.bottom: parent.bottom
                                    anchors.margins: 1
                                    width: Math.max(0, Math.min(parent.width - 2, (modelData.battery || 0) * (parent.width - 2) / 100))
                                    color: getBatteryColor(modelData.battery)
                                    radius: 7
                                }

                                Text {
                                    anchors.centerIn: parent
                                    text: qsTr("%1%").arg(modelData.battery || 0)
                                    color: Styles.Theme.textPrimary
                                    font.pixelSize: 9
                                }
                            }

                            // 充电指示
                            Text {
                                text: modelData.isCharging ? qsTr("⚡充电中") : ""
                                color: Styles.Theme.warning
                                font.pixelSize: 8
                                visible: modelData.isCharging
                            }
                        }

                        Rectangle { width: 1; Layout.fillHeight: true; color: Styles.Theme.border; opacity: 0.3 }

                        // 位置
                        ColumnLayout {
                            Layout.fillWidth: true
                            spacing: 2

                            Text {
                                text: formatPosition(modelData.x, modelData.y)
                                color: Styles.Theme.textPrimary
                                font.pixelSize: Styles.Theme.fontSizeSmall
                                elide: Text.ElideRight
                            }

                            Text {
                                text: modelData.currentStation || qsTr("路径中")
                                color: Styles.Theme.textSecondary
                                font.pixelSize: 10
                                elide: Text.ElideRight
                            }
                        }

                        Rectangle { width: 1; Layout.fillHeight: true; color: Styles.Theme.border; opacity: 0.3 }

                        // 当前任务
                        ColumnLayout {
                            Layout.preferredWidth: 80
                            spacing: 2

                            Text {
                                text: modelData.currentTask || qsTr("无")
                                color: modelData.currentTask ? Styles.Theme.textPrimary : Styles.Theme.textSecondary
                                font.pixelSize: Styles.Theme.fontSizeSmall
                                elide: Text.ElideRight
                                horizontalAlignment: Text.AlignHCenter
                            }

                            // 任务进度
                            Rectangle {
                                Layout.preferredWidth: 60
                                Layout.preferredHeight: 4
                                color: Styles.Theme.backgroundAlternate
                                radius: 2
                                visible: modelData.currentTask && modelData.taskProgress !== undefined

                                Rectangle {
                                    anchors.left: parent.left
                                    anchors.top: parent.top
                                    anchors.bottom: parent.bottom
                                    width: Math.max(0, Math.min(parent.width, (modelData.taskProgress || 0) * parent.width / 100))
                                    color: Styles.Theme.info
                                    radius: 2
                                }
                            }
                        }
                    }

                    // 鼠标交互
                    MouseArea {
                        anchors.fill: parent
                        onClicked: {
                            selectedAgv = modelData
                            agvSelected(modelData)
                        }
                        onDoubleClicked: {
                            agvDoubleClicked(modelData)
                        }
                        onPressAndHold: {
                            showAgvContextMenu(modelData)
                        }
                    }

                    // 悬停效果
                    Rectangle {
                        anchors.fill: parent
                        color: Styles.Theme.primary
                        opacity: 0
                        radius: 2

                        PropertyAnimation {
                            id: hoverAnimation
                            target: parent
                            property: "opacity"
                            duration: 150
                            easing.type: Easing.OutCubic
                        }
                    }

                    MouseArea {
                        anchors.fill: parent
                        hoverEnabled: true
                        onEntered: {
                            if (selectedAgv && modelData.id === selectedAgv.id) return
                            hoverAnimation.to = 0.05
                            hoverAnimation.start()
                        }
                        onExited: {
                            hoverAnimation.to = 0
                            hoverAnimation.start()
                        }
                        onClicked: {
                            selectedAgv = modelData
                            agvSelected(modelData)
                        }
                        onDoubleClicked: {
                            agvDoubleClicked(modelData)
                        }
                    }
                }
            }
        }
    }

    // 上下文菜单
    Menu {
        id: contextMenu
        property var targetAgv: null

        MenuItem {
            text: qsTr("启用AGV")
            enabled: contextMenu.targetAgv && contextMenu.targetAgv.status === "offline"
            onTriggered: agvAction("enable", contextMenu.targetAgv)
        }
        MenuItem {
            text: qsTr("禁用AGV")
            enabled: contextMenu.targetAgv && contextMenu.targetAgv.status !== "offline"
            onTriggered: agvAction("disable", contextMenu.targetAgv)
        }
        MenuSeparator {}
        MenuItem {
            text: qsTr("强制充电")
            enabled: contextMenu.targetAgv && contextMenu.targetAgv.status !== "offline"
            onTriggered: agvAction("charge", contextMenu.targetAgv)
        }
        MenuItem {
            text: qsTr("重置状态")
            enabled: contextMenu.targetAgv && contextMenu.targetAgv.status === "error"
            onTriggered: agvAction("reset", contextMenu.targetAgv)
        }
        MenuSeparator {}
        MenuItem {
            text: qsTr("查看详情")
            onTriggered: agvDoubleClicked(contextMenu.targetAgv)
        }
    }

    // 辅助函数
    function getAgvStatusColor(status) {
        switch(status) {
            case "idle": return Styles.Theme.success
            case "executing": return Styles.Theme.info
            case "charging": return Styles.Theme.warning
            case "error": return Styles.Theme.danger
            case "offline": return Styles.Theme.textSecondary
            default: return Styles.Theme.textSecondary
        }
    }

    function getAgvStatusText(status) {
        switch(status) {
            case "idle": return qsTr("空闲")
            case "executing": return qsTr("执行中")
            case "charging": return qsTr("充电中")
            case "error": return qsTr("故障")
            case "offline": return qsTr("离线")
            default: return qsTr("未知")
        }
    }

    function getAgvStatusIcon(status) {
        switch(status) {
            case "idle": return "✓"
            case "executing": return "⚙"
            case "charging": return "⚡"
            case "error": return "⚠"
            case "offline": return "⊘"
            default: return "?"
        }
    }

    function getBatteryColor(battery) {
        var level = battery || 0
        if (level > 50) return Styles.Theme.success
        if (level > 20) return Styles.Theme.warning
        return Styles.Theme.danger
    }

    function formatPosition(x, y) {
        if (x === undefined || y === undefined) return qsTr("未知位置")
        return qsTr("(%1, %2)").arg(x.toFixed(1)).arg(y.toFixed(1))
    }

    function showAgvContextMenu(agv) {
        contextMenu.targetAgv = agv
        contextMenu.popup()
    }

    function sortAgvs() {
        // TODO: 实现排序逻辑
        console.log("Sort AGVs by", sortColumn, sortAscending ? "ASC" : "DESC")
    }
}